package com.dtda.edu.miaosha.controller;


import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.dtda.edu.miaosha.common.exception.BaseExcpController;
import com.dtda.edu.miaosha.common.exception.BusinessException;
import com.dtda.edu.miaosha.common.response.EmBusinessError;
import com.dtda.edu.miaosha.po.SystemPo;
import com.dtda.edu.miaosha.service.LoginService;

/**
 * @author 袁强
 * @version 2019年3月16日 上午9:26:20
 * 类说明  
 */
@RestController
@RequestMapping("/")
public class SystemLogin extends BaseExcpController{

	@Autowired
	private LoginService loginService;
	
	@RequestMapping("/sysLogin")   //注意与用户登录重名
	public ModelAndView doLogin(){
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("/management/manage");
		return modelAndView;
	}
	@RequestMapping("/loginSystem")   
	public ModelAndView goLogin(HttpServletRequest request,
			              @RequestParam(name="name") String name,
			              @RequestParam(name="password") String password) throws BusinessException{
		ModelAndView modelAndView = new ModelAndView();
		if(StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
			throw new BusinessException(EmBusinessError.PARAM_VALIDATION_ERROR);
		}
		SystemPo systemPo = loginService.selectSystem(name, password);
		if(systemPo == null) {
			modelAndView.setViewName("/management/manage");  //登录失败,重新登录
			return modelAndView;
		}
		request.getSession().setAttribute("system", systemPo);
		modelAndView.addObject("system", systemPo);
		modelAndView.setViewName("/management/home");
		return modelAndView;
	}
	@RequestMapping("/logout")   
	public ModelAndView logout(HttpServletRequest request) {
		SystemPo systemPo =(SystemPo) request.getSession().getAttribute("isOk");
		if(systemPo!=null) {
			request.getSession().invalidate();   //清除session
		}
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("/management/manage");
		return modelAndView;
	}
}
